<template>
    <transition name="fade-top">
        <div class="layer-msg" :class="layerClass" v-show="visible" :style="{'z-index':zIndex}">
            <div class="layer-body">
                <i class="icon" :class="iconClass"></i>
                <div class="message" v-html="message"></div>
            </div>
        </div>
    </transition>
</template>
<script>
    export default {
        name: 'msg',
        data() {
            return {
                visible: false,
                closed: false,
                index: 1,
                type: 'success',
                message: '',
                onClose: null,
                duration: 3000,
                timer: null
            }
        },
        computed: {
            layerClass() {
                return 'layer-msg-' + this.type
            },
            zIndex() {
                return 2000 + this.index
            },
            iconClass() {
                if (this.type == 'center') {
                    return 'i-delete i-info'
                }
                else {
                    return 'i-delete i-' + this.type
                }
            }
        },
        watch: {
            closed(newVal) {
                if (newVal) {
                    this.visible = false
                    this.destroyElement()
                    // this.$el.addEventListener('transitionend', this.destroyElement)
                }
            }
        },
        mounted() {
            this.startTimer()
        },
        methods: {
            destroyElement() {
                // this.$el.removeEventListener('transitionend', this.destroyElement)= 
                setTimeout(() => {
                    this.$destroy(true)
                    this.$el.parentNode.removeChild(this.$el)
                }, 500)
            },
            close() {
                this.closed = true
                if (typeof this.onClose === 'function') {
                    this.onClose(this)
                }
            },
            clearTimer() {
                clearTimeout(this.timer)
            },
            startTimer() {
                if (this.duration > 0) {
                    this.timer = setTimeout(() => {
                        if (!this.closed) {
                            this.close()
                        }
                    }, this.duration)
                }
            }
        }
    }
</script>